package servlet;

import entity.Product;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Miss Chen
 * @version 1.0
 * @date 2024年09月06日10:56
 */

@WebServlet("*.product")
public class ProductServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String path=request.getServletPath();
        if("/findAll.product".equals(path)){
            findAll(request,response);
        }
        if("/findById.product".equals(path)){
            findById(request,response);
        }

    }
    public void findAll(HttpServletRequest request, HttpServletResponse response){
        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        List<Product> products=new ArrayList<>();
        String url="jdbc:mysql://127.0.0.1:3306/shop?useUnicode=true&characterEncoding=utf-8";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn= DriverManager.getConnection(url,"root","root");
            String sql=new StringBuffer()
                    .append(" select id,name,price ")
                    .append(" from t_product ")
                    .toString();
            ps=conn.prepareStatement(sql);
            rs=ps.executeQuery();
            while(rs.next()){
                Product product=new Product();
                product.setId(rs.getInt("id"));
                product.setName(rs.getString("name"));
                product.setPrice(rs.getDouble("price"));
                products.add(product);
            }
            request.setAttribute("products",products);
            // request.getRequestDispatcher("/list.jsp").forward(request,response);
            request.getRequestDispatcher("/jquery/list.jsp").forward(request,response);


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(ps!=null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(rs!=null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void findById(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter out=response.getWriter();
        String id=request.getParameter("id");
        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        String url="jdbc:mysql://127.0.0.1:3306/shop?useUnicode=true&characterEncoding=utf-8";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn= DriverManager.getConnection(url,"root","root");
            String sql=new StringBuffer()
                    .append(" select id,name,price ")
                    .append(" from t_product ")
                    .append(" where id=? ")
                    .toString();
            ps=conn.prepareStatement(sql);
            ps.setInt(1,Integer.parseInt(id));
            rs=ps.executeQuery();
            if(rs.next()){
                Product product=new Product();
                product.setId(rs.getInt("id"));
                product.setName(rs.getString("name"));
                product.setPrice(rs.getDouble("price"));
                // String jsonProduct="{'id':'"+product.getId()+"','name':'"+product.getName()+"','price':'"+product.getPrice()+"'}";
                // out.println(jsonProduct);

                //将一个java对象变成json对象
                JSONObject jsonObject=JSONObject.fromObject(product);
                out.println(jsonObject.toString());

                //将一个Java对象集合转换JSON对象数组
                // List<Product> products=new ArrayList<>();
                // products.add(new Product(1,"aaa",10.0));
                // products.add(new Product(2,"bbb",20.0));
                // products.add(new Product(3,"ccc",30.0));
                // JSONArray jsonArray=JSONArray.fromObject(products);
                // out.println(jsonArray.toString());
            }


        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
